﻿using AutoMapper;

using PLCS.Application.Contracts.EquipmentApp.Dtos;
using PLCS.Application.Contracts.LogShowApp;
using PLCS.Application.Contracts.LogShowApp.Dtos;
using PLCS.Domain.Equipments;
using PLCS.Domain.Logs;
using PLCS.Domain.Shared.Enums;

using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.LogShowApp
{
    public class OperationLogAppService : CrudAppService<OperationLog, OperationLogDto, Guid, PagedResultRequestDto, OperationLogEditDto>, IOperationLogAppService
    {
        public OperationLogAppService(IRepository<OperationLog, Guid> repository) : base(repository)
        {
        }

        public async Task<PagedResultDto<OperationLogDto>> GetListBySearchAsync(PagedResultRequestDto input, string? startTime, string? endTime, string? view, string? operationType)
        {
            await CheckGetListPolicyAsync();

            var query = await CreateFilteredQueryAsync(input);
            bool isStartTime = DateTime.TryParse(startTime, out DateTime StartDateTime);
            query = query.WhereIf(isStartTime, x => x.CreationTime > StartDateTime);
            bool isEndTime = DateTime.TryParse(endTime, out DateTime EndDateTime);
            query = query.WhereIf(isEndTime, x => x.CreationTime < EndDateTime);
            query = query.OrderByDescending(x => x.CreationTime);
            query = query.WhereIf(!string.IsNullOrEmpty(view), x => x.View == view)
            .WhereIf(!string.IsNullOrEmpty(operationType), x => x.OperationType == operationType);
            var totalCount = await AsyncExecuter.CountAsync(query);

            query = ApplyPaging(query, input);

            var entities = await AsyncExecuter.ToListAsync(query);
            var entityDtos = await MapToGetListOutputDtosAsync(entities);

            return new PagedResultDto<OperationLogDto>(
                totalCount,
                entityDtos
            );
        }

        public async Task UpdateAsync(OperationLogEditDto input)
        {
            await CheckUpdatePolicyAsync();

            var entity = await GetEntityByIdAsync(input.Id);
            await MapToEntityAsync(input, entity);
            await Repository.UpdateAsync(entity, autoSave: true);
        }
    }
}